package spring.boot.adminx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import spring.boot.adminx.model.WxAd;
import spring.boot.adminx.model.WxMiniFirstPage;
import spring.boot.adminx.service.FastDFSService;
import spring.boot.adminx.service.WxAdService;
import spring.boot.adminx.service.WxMiniFirstPageService;

import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/wx/mini/admin/first")
public class WxMiniFirstPageController {

    @Value("${fdfs.http.path}")
    public String path;

    @Autowired
    private FastDFSService fastDFSService;

    @Autowired
    private WxMiniFirstPageService wxMiniFirstPageService;

    @Autowired
    private WxAdService wxAdService;

    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file){
        if (file!=null){
            String fileName = fastDFSService.uploadFile(file);
            return path+fileName;
        }
        return null;
    }

    @GetMapping("list/{wxMiniId}")
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_LIST')")
    public String list(@PathVariable String wxMiniId, Model model){

        QueryWrapper<WxMiniFirstPage> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_mini_app_id",wxMiniId);
        wrapper.orderByAsc("order_num");
        List<WxMiniFirstPage> list = wxMiniFirstPageService.list(wrapper);
        for (int i = 0; i < list.size(); i++) {
            QueryWrapper<WxAd> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("first_page_id",list.get(i).getId());
            queryWrapper.orderByAsc("order_num");
            List<WxAd> wxAds = wxAdService.list(queryWrapper);
            list.get(i).setWxAdList(wxAds);
        }
        model.addAttribute("list",list);
        model.addAttribute("wxMiniAppId",wxMiniId);


        return "firstPage/list";
    }


    @GetMapping("/to/add/{wxMiniAppId}")
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_ADD')")
    public String toAdd(Model model, @PathVariable String wxMiniAppId){
        model.addAttribute("wxMiniAppId",wxMiniAppId);
        return "firstPage/add";
    }

    @PostMapping("insert")
    @ResponseBody
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_ADD')")
    public String insert(String filePath, String wxMiniAppId, Integer type,
                         String url, String openid, Integer orderNum, String remarks){
        WxMiniFirstPage wxMiniFirstPage = new WxMiniFirstPage();
        wxMiniFirstPage.setId(IdWorker.getId());
        wxMiniFirstPage.setPicUrl(filePath);
        wxMiniFirstPage.setWxMiniAppId(Long.valueOf(wxMiniAppId));
        wxMiniFirstPage.setType(type);
        wxMiniFirstPage.setUrl(url);
        wxMiniFirstPage.setOpenid(openid);
        wxMiniFirstPage.setOrderNum(orderNum);
        wxMiniFirstPage.setCreateTime(new Date());
        wxMiniFirstPage.setRemarks(remarks);
        wxMiniFirstPageService.save(wxMiniFirstPage);
        wxMiniFirstPageService.delFirstPageKey(wxMiniAppId);
        return "true";
    }

    @GetMapping("/to/update/{id}")
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_UPDATE')")
    public String toUpdate(Model model, @PathVariable String id){
        model.addAttribute("id",id);
        WxMiniFirstPage wxMiniFirstPage = wxMiniFirstPageService.getById(id);
        model.addAttribute("wxMiniFirstPage",wxMiniFirstPage);
        return "firstPage/edit";
    }


    @PostMapping("update")
    @ResponseBody
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_UPDATE')")
    public String update(String id,String filePath, Integer type,
                         String url, String openid, Integer orderNum, String remarks){
        WxMiniFirstPage wxMiniFirstPage = new WxMiniFirstPage();
        wxMiniFirstPage.setId(Long.valueOf(id));
        wxMiniFirstPage.setPicUrl(filePath);
        wxMiniFirstPage.setType(type);
        wxMiniFirstPage.setUrl(url);
        wxMiniFirstPage.setOpenid(openid);
        wxMiniFirstPage.setOrderNum(orderNum);
        wxMiniFirstPage.setRemarks(remarks);
        wxMiniFirstPageService.updateById(wxMiniFirstPage);
        wxMiniFirstPageService.delFirstPageKey(String.valueOf(wxMiniFirstPageService.selectWxMiniAppIdById(Long.parseLong(id))));
        return "true";
    }



    @PostMapping("delete/{id}")
    @ResponseBody
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_DELETE')")
    public boolean delete(@PathVariable String id){
        UpdateWrapper<WxAd> wxAdUpdateWrapper = new UpdateWrapper<>();
        wxAdUpdateWrapper.eq("first_page_id",id);
        boolean removeAd = wxAdService.remove(wxAdUpdateWrapper);
        log.info("删除广告结果 [{}]",removeAd);
        boolean remove = wxMiniFirstPageService.removeById(id);
        log.info("删除首页链接结果 [{}]",remove);
        wxMiniFirstPageService.delFirstPageKey(String.valueOf(wxMiniFirstPageService.selectWxMiniAppIdById(Long.parseLong(id))));
        return remove;
    }

    @PostMapping("ad/delete/{id}")
    @ResponseBody
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_AD')")
    public boolean adDelete(@PathVariable String id){
        wxMiniFirstPageService.delFirstPageKey(String.valueOf(wxMiniFirstPageService.selectWxMiniAppIdById(wxAdService.selectFirstUrlIdByAdId(Long.parseLong(id)))));
        return wxAdService.removeById(id);
    }



    @PostMapping("ad/{id}/{adId}/{adName}/{type}")
    @ResponseBody
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_AD')")
    public boolean ad(@PathVariable Long id, @PathVariable String adId, @PathVariable String adName, @PathVariable int type){
        WxAd wxAd = new WxAd();
        wxAd.setId(IdWorker.getId());
        wxAd.setCreateTime(new Date());
        wxAd.setFirstPageId(id);
        wxAd.setName(adName);
        wxAd.setOrderNum(99);
        wxAd.setType(type);
        wxAd.setAdId(adId);
        wxMiniFirstPageService.delFirstPageKey(String.valueOf(wxMiniFirstPageService.selectWxMiniAppIdById(id)));
        return wxAdService.save(wxAd);
    }
    
    @PostMapping("enabledOrDisable/{id}/{status}")
    @ResponseBody
    @PreAuthorize("hasRole('WX_MINI_ADMIN_FIRST_UPDATE')")
	public Object enabledOrDisable(@PathVariable Long id, @PathVariable int status) {
		WxMiniFirstPage entity = new WxMiniFirstPage();
		entity.setStatus(status);
		UpdateWrapper<WxMiniFirstPage> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", id);
		boolean success = wxMiniFirstPageService.saveOrUpdate(entity, updateWrapper);
		return success;
	}

}